package com.bitcarton.dynamic.datasource.autoconfigure;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

/**
 * @author wwd
 */
public class TargetUtil {
    private static final Logger log = LoggerFactory.getLogger(TargetUtil.class);

    public static String getTarget(Object proxy) {
        return getTargetString(proxy);

    }


    private static String getTargetString(Object proxy) {
        try {
            Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
            h.setAccessible(true);
            Object o = h.get(proxy);
            Field[] fields = o.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                if ("mapperInterface".equals(field.getName())) {
                    Object mapperInterface = field.get(o);
                    Field[] mf = mapperInterface.getClass().getDeclaredFields();
                    for (Field f : mf) {
                        f.setAccessible(true);
                        if ("name".equals(f.getName())) {
                            return (String) f.get(mapperInterface);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("TargetUtil.getTargetString error", e);
        }
        return null;
    }

}
